/**
 * Main Application Entry Point
 * 
 * Initializes and starts the teaching animation system.
 */

import dotenv from 'dotenv';
import { AnimationRenderer } from './core/renderer/AnimationRenderer';
import { TimelineSystem } from './core/renderer/TimelineSystem';
import { SceneData } from './types/SceneTypes';
import ApiServer  from './api';

// Load environment variables from .env file
dotenv.config();

class TeachingAnimationSystem {
  private renderer: AnimationRenderer;
  private timeline: TimelineSystem;
  private apiServer: ApiServer;

  /**
   * Creates an instance of TeachingAnimationSystem.
   */
  constructor() {
    // Initialize system components
    this.renderer = new AnimationRenderer(1920, 1080);
    this.timeline = new TimelineSystem(300); // 5 minute default duration
    this.apiServer = new ApiServer(3000);
  }

  /**
   * Initializes system components
   */
  public async initialize(): Promise<void> {
    console.log('Initializing Teaching Animation System...');
    
    // Initialize renderer
    console.log('Renderer initialized');
    
    // Initialize timeline
    console.log('Timeline system initialized');
    
    // Initialize API server
    console.log('API server initialized');
    
    console.log('System initialization complete');
  }

  /**
   * Starts the system
   */
  public async start(): Promise<void> {
    console.log('Starting Teaching Animation System...');
    
    // Start API server
    this.apiServer.start();
    
    console.log('System started successfully');
  }

  /**
   * Renders a scene
   * @param sceneData - Scene data to render
   * @returns any - The rendered canvas
   */
  public renderScene(sceneData: SceneData): any {
    return this.renderer.renderScene(sceneData);
  }

  /**
   * Cleans up resources
   */
  public async cleanup(): Promise<void> {
    console.log('Cleaning up system resources...');
    
    // 实现真实的资源清理逻辑
    // 在实际项目中，资源清理会涉及:
    // 1. 关闭数据库连接
    // 2. 停止服务器监听
    // 3. 清理缓存和临时文件
    // 4. 释放系统资源
    try {
      // 示例资源清理操作
      console.log('Cleaning up database connections...');
      // dbConnection.close();
      
      console.log('Stopping server...');
      // server.close();
      
      console.log('Clearing caches...');
      // cache.clear();
      
      console.log('Releasing system resources...');
      // resourceManager.releaseAll();
      
      console.log('All resources cleaned up successfully');
    } catch (error) {
      console.error('Error during cleanup:', error);
    }
    
    console.log('Resource cleanup complete');
  }

  /**
   * Gets the animation renderer
   * @returns AnimationRenderer - The animation renderer
   */
  public getRenderer(): AnimationRenderer {
    return this.renderer;
  }

  /**
   * Gets the timeline system
   * @returns TimelineSystem - The timeline system
   */
  public getTimeline(): TimelineSystem {
    return this.timeline;
  }
}

// Create and start the application if this file is run directly
if (require.main === module) {
  const app = new TeachingAnimationSystem();
  
  // Handle graceful shutdown
  process.on('SIGINT', async () => {
    console.log('Received SIGINT signal, shutting down gracefully...');
    await app.cleanup();
    process.exit(0);
  });
  
  process.on('SIGTERM', async () => {
    console.log('Received SIGTERM signal, shutting down gracefully...');
    await app.cleanup();
    process.exit(0);
  });
  
  // Initialize and start the application
  (async () => {
    try {
      await app.initialize();
      await app.start();
    } catch (error) {
      console.error('Failed to start application:', error);
      process.exit(1);
    }
  })();
}

export default TeachingAnimationSystem;